package com.wqj.kyee.gps.ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.ViewAnimator;

import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Poi;
import com.amap.api.navi.view.PoiInputItemWidget;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.wqj.kyee.gps.R;
import com.wqj.kyee.gps.adapter.ItemSimpleAdapter;
import com.wqj.kyee.gps.adapter.SearchHistoryAdapter;
import com.wqj.kyee.gps.util.AMapUtil;
import com.wqj.kyee.gps.util.BaseTransitionInActivity;
import com.wqj.kyee.gps.util.Constants;
import com.wqj.kyee.gps.util.LoadMoreListView;
import com.wqj.kyee.gps.util.MyLoadingDialog;
import com.wqj.kyee.gps.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class SearchActivity extends AppCompatActivity implements Inputtips.InputtipsListener,
                                        TextView.OnEditorActionListener, View.OnClickListener, PoiSearch.OnPoiSearchListener,
                                        LoadMoreListView.OnLoadMoreListener{

    ViewAnimator mSwitcher;

    private String  city = "北京";
    private ListView mInputList;
    private EditText mKeywordText;
    private TextView mSearchBtn;

    private TextView mFoodTv;
    private TextView mPetrolTv;
    private TextView mHotelTv;

    private boolean isSearchLocation;
    private PoiResult poiResult; // poi返回的结果
    private int currentPage = 1;//
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索
    private MyLoadingDialog myLoadingDialog;
    private LoadMoreListView mLocationList;
    private ArrayList<PoiItem> poiItemsList = new ArrayList<PoiItem>();
    private ItemSimpleAdapter locationAdapter;
    private int pointType;
    private Poi selectedPoi;

    private ListView mHistoryList;
    //private int mCurrentIdx;
    //private int mHistoryItems = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().hide();

        String transition = getIntent().getStringExtra(BaseTransitionInActivity.EXTRA_TRANSITION);
        switch (transition) {
            case   BaseTransitionInActivity.TRANSITION_FADE_FAST:
                Transition transitionFadeFast =
                        TransitionInflater.from(this).inflateTransition(R.transition.fade_fast);
                getWindow().setEnterTransition(transitionFadeFast);
            break;
        }

        city = getIntent().getStringExtra(Constants.EXTRA_CURRENT_CITY);


        mSwitcher = (ViewAnimator) findViewById(R.id.id_va_switcher);
        mInputList = (ListView) findViewById(R.id.inputlist);
        mKeywordText = (EditText) findViewById(R.id.input_edittext);
        mSearchBtn = (TextView) findViewById(R.id.btn_search);
        mLocationList = (LoadMoreListView) findViewById(R.id.id_lv_locationlist);

        mFoodTv = (TextView) findViewById(R.id.id_tv_food);
        mPetrolTv = (TextView) findViewById(R.id.id_tv_petrol);
        mHotelTv = (TextView) findViewById(R.id.id_tv_Hotel);

        mHistoryList = (ListView) findViewById(R.id.id_lv_historylist);
        loadSearchHistory();


        String hint = getIntent().getStringExtra(Constants.EXTRA_HINT);
        if (hint != null) {
            isSearchLocation = true;
            mKeywordText.setHint(hint);
            //mSwitcher.setDisplayedChild(2);

            LinearLayout layout = (LinearLayout) findViewById(R.id.id_ll_around_search);
            layout.setVisibility(View.GONE);
            myLoadingDialog = new MyLoadingDialog();
            locationAdapter = new ItemSimpleAdapter(poiItemsList, this);
            pointType = getIntent().getIntExtra(Constants.EXTRA_POINTTYPE, -1);
        }

        mFoodTv.setOnClickListener(this);
        mPetrolTv.setOnClickListener(this);
        mHotelTv.setOnClickListener(this);

        mKeywordText.addTextChangedListener(textWatcher);
        mKeywordText.setOnEditorActionListener(this);

        mLocationList.setONLoadMoreListener(this);
        mLocationList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                PoiItem item = poiItemsList.get(pos);

                if((pointType == Constants.EXTRA_POI_TYPE_HOME) || (pointType == Constants.EXTRA_POI_TYPE_COMPANY)) {

                    Intent intent = new Intent();
                    intent.putExtra(Constants.EXTRA_POIITEM, item);
                    setResult(Constants.SEARCH_LOCATION_RESULT_CODE, intent);
                    finishAfterTransition();
                    return;
                }

                selectedPoi = new Poi(item.getTitle(), new LatLng(item.getLatLonPoint().getLatitude(), item.getLatLonPoint().getLongitude()), item.getPoiId());

                storeHistory(selectedPoi.getName());
                if (!TextUtils.isEmpty(selectedPoi.getPoiId())) {
                    PoiSearch.Query query = new PoiSearch.Query(selectedPoi.getName(), "", city);
                    query.setDistanceSort(false);
                    query.requireSubPois(true);
                    PoiSearch poiSearch = new PoiSearch(getApplicationContext(), query);
                    poiSearch.setOnPoiSearchListener(SearchActivity.this);
                    poiSearch.searchPOIIdAsyn(selectedPoi.getPoiId());
                }

                //Intent intent = new Intent();
                //intent.putExtra(Constants.EXTRA_POIITEM, item);

                //setResult(Constants.SEARCH_LOCATION_RESULT_CODE, intent);
                //finishAfterTransition();

            }
        });


//        mSwitcher.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                mSwitcher.setFocusable(true);
//                mSwitcher.setFocusableInTouchMode(true);
//                mSwitcher.requestFocus();
//                InputMethodManager imm = (InputMethodManager) Main3Activity.this.getSystemService(Main3Activity.INPUT_METHOD_SERVICE);
//                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//                imm.hideSoftInputFromWindow(mSwitcher.getWindowToken(), 0);
//                return false;
//            }
//        });

        //Slide slide = new Slide(Gravity.L);
        //slide.addTarget(R.id.search_edit_text);

        //getWindow().setEnterTransition(slide);
    }

    //Timer timer = new Timer();
    @Override
    protected void onResume() {
        super.onResume();
        mKeywordText.setFocusable(true);
        mKeywordText.setFocusableInTouchMode(true);
        mKeywordText.requestFocus();
        //this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                InputMethodManager imm = (InputMethodManager) mKeywordText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//                //imm.showSoftInput(mKeywordText,0);
//            }
//        }, 500);
    }

    public void onBackClick(View view) {
        hideSoftWindow();
        //setResult(Constants.SEARCH_NULL_RESULT_CODE);
        this.finishAfterTransition();
    }

    public void onSearchBtnClick(View view) {
        if (!isSearchLocation)
            this.finishWithResult(Constants.SEARCH_RESULT_CODE, AMapUtil.checkEditText(mKeywordText), true);
        else {
            doSearchQuery();
        }
    }

    private void finishWithResult(int resultCode, String keyWord, boolean store) {
        hideSoftWindow();

        if (!keyWord.isEmpty()) {
            Intent intent = new Intent();
            if (store)
                storeHistory(keyWord);
            intent.putExtra(Constants.EXTRA_KEYWORD, keyWord);
            setResult(resultCode, intent);
        }

        this.finishAfterTransition();
    }



    private void hideSoftWindow() {
        InputMethodManager imm = (InputMethodManager) mKeywordText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive())
            imm.hideSoftInputFromWindow(mKeywordText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    private List<String> mHistoryData = new ArrayList<String>();
    private void loadSearchHistory() {


        int idx = 0;
        //int historyItems;
        int currentIdx;

        SharedPreferences items = getSharedPreferences(Constants.History_Preferences, MODE_PRIVATE);

//        historyItems = items.getInt(Constants.SP_KEY_ITEM_NUMS, 0);
//        if (historyItems == 0)
//            return;

        currentIdx = items.getInt(Constants.SP_KEY_CURRENT_INDEX, 0);
        if (currentIdx == 0)
            return;


        for (idx = 1; idx <= Constants.History_Item_MAX_Nums; idx++) {
            String itemId = Constants.SP_KEY_ITEM_PREFIX+idx;

            String content = items.getString(itemId, "");
            if (!content.isEmpty())
                mHistoryData.add(content);
        }

        SearchHistoryAdapter adapter = new SearchHistoryAdapter(getApplicationContext(), mHistoryData);
        mHistoryList.setAdapter(adapter);
        mHistoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String content = mHistoryData.get(i);

                if (!isSearchLocation)
                    finishWithResult(Constants.SEARCH_RESULT_CODE, content, false);
                else {
                    mKeywordText.setText(content);
                    doSearchQuery();
                }
            }
        });
        adapter.notifyDataSetChanged();
    }

    private void storeHistory(String content) {

        SharedPreferences items = getSharedPreferences(Constants.History_Preferences, MODE_PRIVATE);
        SharedPreferences.Editor editor = items.edit();

        //int historyItems;
        int currentIdx;

        currentIdx = items.getInt(Constants.SP_KEY_CURRENT_INDEX, 1);

        //historyItems = items.getInt(Constants.SP_KEY_ITEM_NUMS, 0);

        String itemId = Constants.SP_KEY_ITEM_PREFIX + currentIdx;

        editor.putString(itemId, content);

        currentIdx += 1;
        if (currentIdx > Constants.History_Item_MAX_Nums) {
            currentIdx = 1;
        }

//        historyItems += 1;
//        if (historyItems > Constants.History_Item_MAX_Nums)
//            historyItems = Constants.History_Item_MAX_Nums;

        editor.putInt(Constants.SP_KEY_CURRENT_INDEX, currentIdx);
//        editor.putInt(Constants.SP_KEY_ITEM_NUMS, historyItems);

        editor.commit();
    }



    private void doSearchQuery() {

        myLoadingDialog.show(getFragmentManager(), "Loading");

        query = new PoiSearch.Query(AMapUtil.checkEditText(mKeywordText), "", city);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
        //query.setDistanceSort(true);
        query.setCityLimit(true);

        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();

    }

    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

            if (s.length() > 0) {
                //if (isSearchLocation) {
                    //mSwitcher.setDisplayedChild(2);
               //     String keyWord = AMapUtil.checkEditText(mKeywordText);
               //     if (!keyWord.isEmpty()) {
               //         myLoadingDialog.show(getFragmentManager(), "Loading");

               //         currentPage = 1;
               //         poiItemsList.clear();

                //        doSearchQuery();
                //    }

                //} else {
                {

                    mSwitcher.setDisplayedChild(1);

                    final ScaleAnimation animation = new ScaleAnimation(0.0f, 1.0f, 1.0f, 1.0f,
                            Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 1.0f);
                    animation.setDuration(500);//设置动画持续时间

                    mSearchBtn.startAnimation(animation);
                    mSearchBtn.setVisibility(View.VISIBLE);

                    String newText = s.toString().trim();
                    InputtipsQuery inputtipsQuery = new InputtipsQuery(newText, city);
                    inputtipsQuery.setCityLimit(true);

                    Inputtips inputtips = new Inputtips(SearchActivity.this, inputtipsQuery);
                    inputtips.setInputtipsListener(SearchActivity.this);
                    inputtips.requestInputtipsAsyn();
                }

            } else {
                //if (!isSearchLocation) {
                    mSwitcher.setDisplayedChild(0);
                    mSearchBtn.setVisibility(View.GONE);
                //}
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    private List<HashMap<String, String>> mInputsTipList;
    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            List<HashMap<String, String>> listString = new ArrayList<HashMap<String, String>>();

            for (int i = 0; i < tipList.size(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("name", tipList.get(i).getName());
                if (tipList.get(i).getAddress().isEmpty())
                    map.put("address", tipList.get(i).getDistrict());
                else
                    map.put("address", tipList.get(i).getAddress());
                //Log.e("Inputtip", tipList.get(i).getAdcode() + ", " +
                //tipList.get(i).getAddress() + ", " + "," + tipList.get(i).getPoint().toString());
                listString.add(map);
            }

            mInputsTipList = listString;

            SimpleAdapter aAdapter = new SimpleAdapter(getApplicationContext(), listString, R.layout.item_layout,
                    new String[] {"name","address"}, new int[] {R.id.poi_field_id, R.id.poi_value_id});

            mInputList.setAdapter(aAdapter);

            mInputList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    HashMap<String, String> map = mInputsTipList.get(i);
                    if (!isSearchLocation)
                        finishWithResult(Constants.SEARCH_RESULT_CODE, map.get("name"), true);
                    else {
                        mKeywordText.setText(map.get("name"));
                        doSearchQuery();
                    }
                }
            });
            aAdapter.notifyDataSetChanged();
        } else {
            //Log.e("AMapText", "iputtips error: " + rCode);
            ToastUtil.showerror(getApplicationContext(), rCode);
        }
    }

    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            if (!isSearchLocation)
                this.finishWithResult(Constants.SEARCH_RESULT_CODE, AMapUtil.checkEditText(mKeywordText), true);
            else {
                doSearchQuery();
            }
        }
        return true;
    }

    @Override
    public void onClick(View view) {

        String keyWord = "";
        if (view.getId() == R.id.id_tv_food) {
            keyWord = mFoodTv.getText().toString();
        } else if (view.getId() == R.id.id_tv_petrol) {
            keyWord= mPetrolTv.getText().toString();
        } else if (view.getId() == R.id.id_tv_Hotel) {
            keyWord = mHotelTv.getText().toString();
        }

        this.finishWithResult(Constants.SEARCH_ARROUND_RESULT_CODE, keyWord, false);
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        myLoadingDialog.dismiss();

        mSwitcher.setDisplayedChild(2);

        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    // 取得搜索到的poiitems有多少页
                    List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始

                    if (poiItems != null && poiItems.size() > 0) {
                        for (PoiItem item : poiItems) {
                            poiItemsList.add(item);
                        }

                        mLocationList.setAdapter(locationAdapter);
                        locationAdapter.notifyDataSetChanged();
                        //if (locationAdapter.getCount() > 10)
                        //    mLocationList.setSelection(locationAdapter.getCount() - 10);
                        mLocationList.setLoadCompleted();
 
                    } else {
                        ToastUtil.show(this,
                                R.string.no_result);
                        mLocationList.setLoadFinished();
                    }
                }
            } else {
                ToastUtil.show(this,
                        R.string.no_result);
            }
        } else {
            ToastUtil.showerror(this, rCode);
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int errorCode) {
        try {
            LatLng latLng = null;
            //int code = 0;
            if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
                if (poiItem == null) {
                    return;
                }
                LatLonPoint exitP = poiItem.getExit();
                LatLonPoint enterP = poiItem.getEnter();
                if (pointType == PoiInputItemWidget.TYPE_START) {
                    //code = 100;
                    if (exitP != null) {
                        latLng = new LatLng(exitP.getLatitude(), exitP.getLongitude());
                    } else {
                        if (enterP != null) {
                            latLng = new LatLng(enterP.getLatitude(), enterP.getLongitude());
                        }
                    }
                }
                if (pointType == PoiInputItemWidget.TYPE_DEST) {
                    //code = 200;
                    if (enterP != null) {
                        latLng = new LatLng(enterP.getLatitude(), enterP.getLongitude());
                    }
                }
            }
            Poi poi;
            if (latLng != null) {
                poi = new Poi(selectedPoi.getName(), latLng, selectedPoi.getPoiId());
            } else {
                poi = selectedPoi;
            }
            Intent intent = new Intent();
            intent.putExtra(Constants.EXTRA_POI, poi);
            setResult(Constants.SEARCH_LOCATION_RESULT_CODE, intent);
            finishAfterTransition();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onloadMore() {
        if (poiResult.getPageCount() <= currentPage) {
            mLocationList.setLoadFinished();
            return;
        }

        currentPage++;
        doSearchQuery();
    }
}
